/**
 * Created by lihao on 2017/3/7.
 */
//列表服务
"use strict";
var Promise = require('bluebird');
var ApiService = require('./ApiService');

module.exports = function () {
    var config = {};
    var listParams = {};
    var pageTotal = 0;
    var page = 1;
    return {
        init:function (conf,pageTotal) {
            listParams = conf.params;
            pageTotal = pageTotal;
            return Promise.resolve(listParams);
        },
        setConfig:function (conf) {
            config = conf;
            return Promise.resolve(config);
        },
        getConfig:function () {
            return config;
        },
        refresh:function () {
            return ApiService.postApi(config.post,listParams)
                .then(ApiService.error)
                .then(function (data) {
                    pageTotal = data.data.pageCount;
                    page = listParams.pageNumber;
                    if(!_.isEmpty(config.listName)){
                        _.set(data,'list',_.get(data,config.listName));
                    }
                    return Promise.resolve(data);
                })
        },
        pageStatus:function () {
            return {
                totalPage:pageTotal,
                nextPage: page + 1 > pageTotal ? 0 : page + 1,
                prevPage: page - 1 == 0 ? 1 : page - 1,
            }
        },
        setParams:function (type,value) {
            _.set(listParams,type,value);
            return Promise.resolve(true);
        },
        getParams:function (type) {
            return _.result(listParams,type);
        },
        setListParams:function (data) {
            listParams = $.extend(listParams,data);
            return Promise.resolve(listParams);
        },
        getListParams:function () {
            return listParams;
        },
        clearParams:function (arr) {
            if(_.isEmpty(arr)){
                listParams = config.params;
                pageTotal = 0;
                page = 1;
            }else{
                _.map(arr,function (item) {
                    _.set(listParams,item,'');
                });
                _.set(listParams,'pageNumber',1);
                pageTotal = 0;
                page = 1;
            }
            return Promise.resolve(true);
        }
    }
}();